package gitlabapi

import (
	"encoding/json"
	"fmt"
	"github.com/sirupsen/logrus"
	"gitlab-sync/config"
	"gitlab-sync/util"
)

type Users struct {
	Id                 int    `json:"id"`
	Name               string `json:"name"`
	UserName           string `json:"username"`
	State              string `json:"state"`
	Email              string `json:"email"`
	Commit_email       string `json:"commit_email"`
	Is_admin           bool   `json:"is_admin"`
	Password           string `json:"password"`
	Projects_limit     int    `json:"projects_limit"`
	Can_create_group   bool   `json:"can_create_group"`
	Can_create_project bool   `json:"can_create_project"`
	Skip_confirmation  bool   `true`
	Private_profile    bool   `json:"private_profile"`
}

// 创建用户
func CreateUsers(search string) []Users {
	logrus.Print("开始同步用户")
	var page = 1
	//循环获取分组，直到没有数据
	var result []Users
	for page > 0 {
		url := fmt.Sprintf(config.GetConfig().Gitlab.OriginRemoteUrl+config.GetConfig().Gitlab.UsersApi+"?private_token="+config.GetConfig().OriginGitlab.PrivateToken+"&page=%d", page)
		if search != "all" {
			url = fmt.Sprintf(url+"&search=%s", search)
		}
		body := util.Get(url, config.GetConfig().Log.RequestLog)
		var users []Users
		err := json.Unmarshal(body, &users)
		if err != nil {
			logrus.Error("Error:%s", err)
			return nil
		}
		var i = 1
		if len(users) == 0 {
			logrus.Print("--------------[end]---------------")
			break
		}
		for _, users := range users {
			pwd := users.UserName
			if len(pwd) < 8 {
				pwd = users.Name + "123456"
			}
			users.Password = pwd
			users.Skip_confirmation = true
			newUser := ExecCreateUser(i, users)
			result = append(result, newUser)
			i++
		}
		page++
		if search != "all" {
			page = 0
		}
	}
	logrus.Print("同步用户结束")
	return result
}

// 执行创建
func ExecCreateUser(index int, users Users) Users {
	logrus.Printf("user:%s,username:%s", users.Name, users.UserName)
	logrus.Print("开始同步")
	url := fmt.Sprintf(config.GetConfig().Gitlab.TargetRemoteUrl + config.GetConfig().Gitlab.UsersApi)
	bytesData, _ := json.Marshal(users)
	body := util.Post(url, bytesData, config.GetConfig().TargetGitlab.PrivateToken, config.GetConfig().Log.RequestLog)
	var user Users
	err := json.Unmarshal(body, &user)
	if err != nil {
		logrus.Error("Error:", err)
	}
	logrus.Print("同步完成")
	return user
}
